package com.zerowidth.db.op;

import com.zerowidth.db.DBHelper;
import com.zerowidth.db.base.SqlResult;
import com.zerowidth.db.utils.IOUtils;
import com.zerowidth.db.utils.TimeUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

public class ActiveDB {

    public static boolean insert(String activeCode, int vipType) {
        String time = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);

        String sql = String.format(Locale.getDefault(), "INSERT INTO active_code (active_code, vip_type," +
                        " create_time) VALUES ('%s', %d, '%s')",
                activeCode, vipType, time);

        return DBHelper.executeInsert(sql) > 0;
    }

    public static boolean update(String activeCode, String userId) {
        String sql = String.format("UPDATE active_code SET active_user_id = '%s' WHERE active_code = '%s'",
                userId, activeCode);

        return DBHelper.executeUpdate(sql) > 0;
    }

    public static int findVipType(String activeCode) {
        String sql = String.format("SELECT * FROM active_code WHERE active_code = '%s'" +
                " AND active_user_id IS NULL", activeCode);

        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            if (sr == null) {
                return -1;
            }

            ResultSet rs = sr.rs;
            if (rs.next()) {
                return rs.getInt("vip_type");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return -1;
    }

    public static int findVipType2(String activeCode) {
        String sql = String.format("SELECT * FROM active_code WHERE active_code = '%s'", activeCode);

        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            if (sr == null) {
                return -1;
            }

            ResultSet rs = sr.rs;
            if (rs.next()) {
                return rs.getInt("vip_type");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return -1;
    }

    public static String findActiveUserId(String activeCode) {
        String sql = String.format("SELECT * FROM active_code WHERE active_code LIKE '%%%s%%'" +
                " AND active_user_id IS NOT NULL", activeCode);

        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            if (sr == null) {
                return null;
            }

            ResultSet rs = sr.rs;
            if (rs.next()) {
                return rs.getString("active_user_id");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return null;
    }

}
